class CitiesController < ApplicationController

  def get_country_states    
	puts 'country:' + params['country_id']
    if params['country_id'] == '-1'
      @states = []
    else
      @states = State.find_all_by_country_id(params['country_id'], :order=>:name)
    end
    render :partial=>'cities/update_states' , :layout=>false
  end

  # GET /cities
  # GET /cities.xml
  def index
    @cities = City.all
    
    respond_to do |format|
      format.html # index.html.erb
      format.xml  { render :xml => @cities }
    end
  end

  # GET /cities/1
  # GET /cities/1.xml
  def show
    @city = City.find(params[:id])

    respond_to do |format|
      format.html # show.html.erb
      format.xml  { render :xml => @city }
    end
  end

  # GET /cities/new
  # GET /cities/new.xml
  def new
    @city = City.new

    @countries = Country.find(:all, :order=>:name)
    @states = []

    respond_to do |format|
      format.html # new.html.erb
      format.xml  { render :xml => @city }
    end
  end

  # GET /cities/1/edit
  def edit
    @city = City.find(params[:id])

    @countries = Country.find(:all, :order=>:name)
    @states = State.find_all_by_country_id(@city.state.country.id, :order=>:name)
    @city_country_id = @city.state.country.id
  end

  # POST /cities
  # POST /cities.xml
  def create        
    @city = City.new(params[:city])
    #@countries = Country.find(:all, :order=>:name)
    @states = []
    
    respond_to do |format|
      if @city.save
        flash[:notice] = 'City was successfully created.'
        format.html { redirect_to(@city) }
        format.xml  { render :xml => @city, :status => :created, :location => @city }
      else
        format.html { render :action => "new" }
        format.xml  { render :xml => @city.errors, :status => :unprocessable_entity }
      end
    end
  end

  # PUT /cities/1
  # PUT /cities/1.xml
  def update    
    @city = City.find(params[:id])

    @countries = Country.find(:all, :order=>:name)
    puts "EL VALOR DEL ESTADO ID ES: #{@city.state.id}"
    puts "PARAMETROS: #{params[:city]}"
    
    if !@city.state.nil?
      @states = State.find_all_by_country_id(@city.state.country.id, :order=>:name)
      @city_country_id = @city.state.country.id
    else
      @states =[]
      @city_country_id = nil
    end
        
    respond_to do |format|
      if @city.update_attributes(params[:city])
        flash[:notice] = 'City was successfully updated.'
        format.html { redirect_to(@city) }
        format.xml  { head :ok }
      else
        format.html { render :action => "edit" }
        format.xml  { render :xml => @city.errors, :status => :unprocessable_entity }
      end
    end
  end

  # DELETE /cities/1
  # DELETE /cities/1.xml
  def destroy
    @city = City.find(params[:id])
    @city.destroy

    respond_to do |format|
      format.html { redirect_to(cities_url) }
      format.xml  { head :ok }
    end
  end
end
